/*
Copyright (c) 2010, web2express.org
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the web2express.org nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * connection to social monitor api.
 */
public class SocialMonitor {

  //monitor api url
  private String url = null;       //'http://realmon9.appspot.com/api?act=leads&appid=social2leadXrealmon9';
  private integer timeout = 30000; //http timeout, ms
  private integer retry_count = 0; //http retries
  private integer max_retry = 3;   //max number of retries

  private List<Lead> newleads;     //auto-created new leads

  //create connection to social monitor
  public SocialMonitor(){
    try{
      List<Social2LeadsConfig__C> configs = Social2LeadsConfig__C.getAll().values();
      system.assert(configs.size() > 0);
      url = configs[0].Monitor_API_URL__c + '?act=leads&appid=' + configs[0].API_appid__c;
      system.assertNotEquals(url, null);
      newleads = new List<Lead>();
    }catch(Exception e){
      system.debug('monitor api url is not set: '+url);
    }
  }

  //fetch and parse leads from monitor api; create new leads
  public void fetchLeads(){
    try{
        //fetch feeds
        Http h = new Http();

        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setTimeout(timeout);
        req.setMethod('GET');

        system.debug('fetch leads from '+url);
        HttpResponse resp = h.send(req);
        integer code = resp.getStatusCode();
        if(code == 200){  //success
            system.assertEquals(code, 200);
            //parse feeds
            XmlDom doc = new XmlDom(resp.getBody().trim());
            //system.debug(doc.toXmlString());
            XmlDom.Element e_error = doc.getElementByTagName('error');
            XmlDom.Element e_null = doc.getElementByTagName('null');
            if(e_error != null){
              system.debug('error in response');
              system.assertNotEquals(e_error, null);
            }else if( e_null != null){
              system.debug('null in response');
              system.assertNotEquals(e_null, null);
            }else{
              XmlDom.Element[] elements = doc.getElementsByTagName('lead');
              system.assertNotEquals(elements, null);
              if(elements != null) {
                for(XmlDom.Element element : elements) {
                  //element.dumpAll();
                  if(newleads.size() == 3) break;  //for testing only
                  Lead lead = createNewLead(element);
                  if(lead != null){
                    newleads.add(lead);
                    system.assertNotEquals(lead, null);
                  }
                }
                system.debug('created new leads: '+newleads.size());
              }
            }
        }
    }catch(CalloutException e){
        if(retry_count++ < max_retry){  //time out, retry
          system.debug('retry ...');
          fetchLeads();
        }
    }
  }

  //get new leads
  public List<Lead> getLeads(){return newleads;}

  //create new lead from element
  public Lead createNewLead(XmlDom.Element element){
    try{
        //last name is required
        if(element.getAttribute('last_name') == null){
            return null;
        }
        Lead lead = new Lead();
        lead.LastName = element.getAttribute('last_name');
        //company is required
        if(element.getAttribute('company') == null){
          lead.Company = lead.Lastname;
        }else{
          lead.Company = element.getAttribute('company');
        }
        system.assertNotEquals(lead.LastName, null);
        system.assertNotEquals(lead.Company, null);

        //optional:
        //lead.FirstName = element.getAttribute('first_name');
        lead.MonitorURL__c = element.getAttribute('monitor_url');
        if(element.getAttribute('email') != null){
          lead.Email = element.getAttribute('email');
        }
        lead.LeadSource = 'social media';

        //check if it's new
        List<Lead> leads;
        if(lead.Email != null){
          leads = [SELECT LastName, Company, Email FROM Lead WHERE LastName = :lead.LastName and Company=:lead.Company and Email=:lead.Email];
        }else{
          leads = [SELECT LastName, Company, Email FROM Lead WHERE LastName = :lead.LastName and Company=:lead.Company];
        }
        if(leads.isEmpty()){
          system.assert(leads.size() == 0);
          //create new lead
          system.debug('new lead: '+lead.FirstName+', '+lead.LastName+', '+lead.MonitorURL__c+', '+lead.Company+', '+lead.Email);
          insert lead;
          if(lead.Email != null){
            List<Lead> leads2 = [SELECT LastName, Company, Email FROM Lead WHERE LastName = :lead.LastName and Company=:lead.Company and Email=:lead.Email];
            system.assert(leads2.size() == 1);
          }else{
            List<Lead> leads2 = [SELECT LastName, Company, Email FROM Lead WHERE LastName = :lead.LastName and Company=:lead.Company];
            system.assert(leads2.size() == 1);
          }
          return Lead;
        }
    }catch(Exception e){
      system.debug('failed to create lead from element');
    }

    return null;
  }

  public static testMethod void myTest() {
    SocialMonitor sm = new SocialMonitor();
    sm.fetchLeads();
    List<Lead> leads = sm.getLeads();
    for(Lead lead:leads){
      if(lead.Email != null){
        List<Lead> leads2 = [SELECT LastName, Company, Email FROM Lead WHERE LastName = :lead.LastName and Company=:lead.Company and Email=:lead.Email];
        system.assert(leads2.size() == 1);
      }else{
        List<Lead> leads2 = [SELECT LastName, Company, Email FROM Lead WHERE LastName = :lead.LastName and Company=:lead.Company];
        system.assert(leads2.size() == 1);
      }
    }
  }


}